package com.bulletelc.apollopre.module.main.center.orders.detail;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.entity.OrderDataBean;
import com.bulletelc.apollopre.entity.OrderDetailBean;
import com.bulletelc.apollopre.eventbus.CutPriceProtocolEventBus;
import com.bulletelc.apollopre.framework.MVPBaseActivity;
import com.bulletelc.apollopre.module.deal.pay.PayCenterActivity;
import com.bulletelc.apollopre.module.display.product.details.ProductDetailsActivity;
import com.bulletelc.apollopre.module.main.center.orders.orderComment.FinishCommentActivity;
import com.bulletelc.apollopre.module.web.WebPageActivity;
import com.bulletelc.apollopre.utils.MyUtil;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.bulletelc.apollopre.widget.CustomListView;
import com.bulletelc.apollopre.widget.FoolBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * author: lhl
 * date  : 2018/01/24
 * desc  : 订单详情界面
 */

public class OrderDetailActivity extends MVPBaseActivity<OrderDetailContract.View, OrderDetailPresenter> implements OrderDetailContract.View,
        View.OnClickListener, AdapterView.OnItemClickListener, FoolBar.ClickCallback {

    // views
    private FoolBar flBar;
    private TextView tvStateLabel, tvTime, tvReceiver, tvPhone, tvAddress, tvTotalMoney, tvInvoiceLabel, tvInvoiceTitle,
            tvOrderCode, tvPaymentType, tvCreateAt, tvPayHint, tvPayMoney, tvInstallFee;
    private CustomListView lvOrder;
    private RelativeLayout rlToPay;
    private Button btnGoToPay, btnGoTo, btnCutPrice;
    private LinearLayout llInstallFeePanel;

    // data
    private String orderCode; // 订单ID
    private int group; // 砍价
    private List<OrderDetailBean.SalesOrderItemsBean> salesOrderItemsBeans;
    private OrderListAdapter adapter;
    private OrderDetailBean orderDetailBean;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this); //取消注册事件
    }

    @Override
    public int getLayoutRes() {
        return R.layout.order_detail_activity;
    }

    @Override
    public void assignViews() {
        flBar = findViewById(R.id.flBar);
        flBar.setTitle(this.getResources().getString(R.string.order_detail));
        tvStateLabel = (TextView) findViewById(R.id.tvStateLabel);
        tvTime = (TextView) findViewById(R.id.tvTime);
        tvReceiver = (TextView) findViewById(R.id.tvReceiver);
        tvPhone = (TextView) findViewById(R.id.tvPhone);
        tvAddress = (TextView) findViewById(R.id.tvAddress);
        lvOrder = (CustomListView) findViewById(R.id.lvOrder);
        tvTotalMoney = findView(R.id.tvTotalMoney);
        tvInvoiceLabel = (TextView) findViewById(R.id.tvInvoiceLabel);
        tvInvoiceTitle = (TextView) findViewById(R.id.tvInvoiceTitle);
        tvOrderCode = (TextView) findViewById(R.id.tvOrderCode);
        tvPaymentType = (TextView) findViewById(R.id.tvPaymentType);
        tvCreateAt = (TextView) findViewById(R.id.tvCreateAt);
        rlToPay = (RelativeLayout) findViewById(R.id.rlToPay);
        tvPayHint = (TextView) findViewById(R.id.tvPayHint);
        tvPayMoney = (TextView) findViewById(R.id.tvPayMoney);
        btnGoToPay = (Button) findViewById(R.id.btnGoToPay);
        btnGoTo = findView(R.id.btnGoTo);
        btnCutPrice = findView(R.id.btnCutPrice);
        tvInstallFee = findView(R.id.tvInstallFee);
        llInstallFeePanel = findView(R.id.llInstallFeePanel);
    }
    @Override
    public void setListener() {
        flBar.setClickCallback(this);
        btnGoToPay.setOnClickListener(this);
        btnGoTo.setOnClickListener(this);
        lvOrder.setOnItemClickListener(this);
        btnCutPrice.setOnClickListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {

        // 注册EventBus
        EventBus.getDefault().register(this);//finish();

        Intent intent = getIntent();
        if (intent != null) {
            orderCode = intent.getStringExtra(IntentCode.EXTRA_KEY_ORDER_ID);
        }
        salesOrderItemsBeans = new ArrayList<>();
        adapter = new OrderListAdapter(this, salesOrderItemsBeans, -1);
        lvOrder.setAdapter(adapter);
        //getOrderDetail();
        presenter.getOrderDetail(orderCode);
    }


    @Override
    protected OrderDetailPresenter createPresenter() {
        return new OrderDetailPresenter();
    }

    @Override
    public void onSuccess(OrderDetailBean orderDetailBean) {
        if (orderDetailBean != null) {
            Log.i("data-----11", orderDetailBean.getInvoice_type() + "");
            this.orderDetailBean = orderDetailBean;
            setData(orderDetailBean);
        } else {
            Toast.makeText(this, "数据错误", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onFail(String fail) {
        Toast.makeText(this, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(String error) {
        ToastUtil.showLongToast(this, R.string.network_msg);
    }

    @Override
    public void onSuccessConfirmSign() {
        btnGoTo.setVisibility(View.GONE);
        tvStateLabel.setText("买家已签收");
    }

    @Override
    public void onFailConfirmSign(String fail) {
        Toast.makeText(this, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorConfirmSign(String error) {
        ToastUtil.showLongToast(this, R.string.network_msg);
    }

    /**
     * 设置返回的数据
     *
     * @param orderDetailBean
     */
    private void setData(OrderDetailBean orderDetailBean) {
        tvStateLabel.setText(orderDetailBean.getState_label());
        tvTime.setText(orderDetailBean.getCreated_at());
        tvReceiver.setText(orderDetailBean.getUser_name());
        tvPhone.setText(orderDetailBean.getPhone());
        tvAddress.setText("收货地址: " + orderDetailBean.getAddress());
        tvTotalMoney.setText("¥" + orderDetailBean.getSub_total());
        if(orderDetailBean.getInvoice_type() ==1){
            tvInvoiceLabel.setText("公司");
        }else {
            tvInvoiceLabel.setText("个人");
        }
        tvInvoiceTitle.setText(orderDetailBean.getInvoice_label());
        tvOrderCode.setText(orderDetailBean.getCode());
        tvPaymentType.setText(orderDetailBean.getPayment_label());
        tvCreateAt.setText(orderDetailBean.getCreated_at());
        tvPayMoney.setText("¥" + orderDetailBean.getGrand_total());
        if (orderDetailBean.getInstall_price() != "0") {
            llInstallFeePanel.setVisibility(View.VISIBLE);
            tvInstallFee.setText("¥" + orderDetailBean.getInstall_price());
        }

        salesOrderItemsBeans.clear();
        if (orderDetailBean.getSales_order_items() != null) {
            salesOrderItemsBeans.addAll(orderDetailBean.getSales_order_items());
            adapter.setOrderState(orderDetailBean.getState());
            adapter.notifyDataSetChanged();
        }

        adapter.setOrderId(orderDetailBean.getId());
        group = orderDetailBean.getIs_group();

        switch (orderDetailBean.getState()) {

            case GlobalConfig.ORDER_STATE_UN_PAID: //待付款
                //btnCutPrice.setVisibility(View.VISIBLE); // 测试砍价入口
                tvStateLabel.setText("等待买家付款");
                rlToPay.setVisibility(View.VISIBLE);
                break;

            case GlobalConfig.ORDER_STATE_UN_SEND: //待发货
                checkGroup();
                //rlToPay.setVisibility(View.VISIBLE);
                tvStateLabel.setText("等待卖家发货");
                break;

            case GlobalConfig.ORDER_STATE_UN_SIGN: //待签收
                checkGroup();
                btnGoTo.setVisibility(View.VISIBLE);
                tvStateLabel.setText("等待买家签收");
                btnGoTo.setText("确认签收");
                break;

            case GlobalConfig.ORDER_STATE_AFTER_SALE://售后中
                tvStateLabel.setText("售后中");
                break;

            case GlobalConfig.ORDER_STATE_COMPLETE://完成
                tvStateLabel.setText("订单已完成");
                if (GlobalConfig.ORDER_STATE_UN_COMMENT == orderDetailBean.getComment_state()) {
                    btnGoTo.setVisibility(View.VISIBLE);
                    btnGoTo.setText("评论");
                }
                break;

        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btnGoToPay:
                goToPay();
                break;

            case R.id.btnGoTo:
                goTo();
                break;

            case R.id.btnCutPrice:
                cutPrice();
                break;
        }
    }

    /**
     * 去付款
     */
    private void goToPay() {
        if (orderDetailBean != null) {
            OrderDataBean dataBean = new OrderDataBean();
            dataBean.setId(orderDetailBean.getId());
            dataBean.setCode(orderDetailBean.getCode());
            dataBean.setGrand_total(Double.valueOf(orderDetailBean.getGrand_total()));
            Intent intent = new Intent(this, PayCenterActivity.class);
            intent.putExtra(IntentCode.EXTRA_KEY_ORDER_DATA, dataBean);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(this, "无法付款", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 去签收/评价
     */
    private void goTo() {
        if (orderDetailBean != null) {

            switch (orderDetailBean.getState()) {
                case GlobalConfig.ORDER_STATE_UN_SIGN:
                    confirmSign();
                    break;

                case GlobalConfig.ORDER_STATE_COMPLETE:
                    commentOrder();
                    break;
            }
        }
    }

    /**
     * 签收
     */
    private void confirmSign() {
        JSONObject object = new JSONObject();
        final String json;
        try {
            object.put("state", GlobalConfig.ORDER_STATE_COMPLETE);
            object.put("id", orderDetailBean.getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        json = object.toString();

        AlertDialog dialog = new AlertDialog.Builder(this)
                .setMessage("您确认签收?\n确定后，金额将会转给卖家哦")
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (json != null) {
                            presenter.confirmSign(json);
                        } else {
                            Toast.makeText(OrderDetailActivity.this, "请求参数错误", Toast.LENGTH_SHORT).show();
                        }
                    }
                }).create();

        dialog.show();

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, ProductDetailsActivity.class);
        intent.putExtra(IntentCode.EXTRA_KEY_PRODUCT_ID, salesOrderItemsBeans.get(position).getProduct_id());
        startActivity(intent);
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {

    }

    /**
     * 接受微信授权处理事件
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CutPriceProtocolEventBus event) {
        if (event.getCode() == 1) {
            group = 1;
            btnCutPrice.setText(R.string.order_detail_cut_price_track);
        }
    }
    /**
     * 跳转砍价WebPage
     */
    private void cutPrice() {
        Intent intent = new Intent(this, WebPageActivity.class);
        intent.putExtra(IntentCode.EXTRA_CUT_PRICE_GROUP, group);
        intent.putExtra(IntentCode.EXTRA_KEY_ORDER_ID, orderCode);
        intent.putExtra(IntentCode.EXTRA_KEY_URL, NetWorkPath.GET_BARGAIN_AGREEMENT);
        intent.putExtra(IntentCode.EXTRA_WEB_PAGE_FLAG, GlobalConfig.WEB_PAGE_FOR_CUT_PRICE_AGREEMENT);
        startActivity(intent);
    }

    /**
     *评价订单
     */
    private void commentOrder() {
        Intent intent = new Intent(this, FinishCommentActivity.class);
        String orderId = orderDetailBean.getId();
        intent.putExtra(IntentCode.EXTRA_KEY_ORDER_ID, orderId);
        startActivity(intent);
        finish();
    }

    /**
     * 是否开启砍价入口
     */
    private void checkGroup() {
        if (orderDetailBean.getEnable_group() == 1 && orderDetailBean.getInstall_price() != "0") {
            btnCutPrice.setVisibility(View.VISIBLE);
            // 判断砍价状态
            switch (orderDetailBean.getGroup_state()) {
                case 10:
                    btnCutPrice.setText(R.string.order_detail_cut_price_track);
                    break;
                case 20:
                    btnCutPrice.setText(R.string.order_detail_cut_price_success);
                    break;
                case 30:
                    btnCutPrice.setText(R.string.order_detail_cut_price_fail);
                    break;
            }
        }
    }

}
